package enterprise.web.tookit.user;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import enterprise.web.tookit.generic.GenericDaoImpl;

/**
 * @since 24/12/2012
 * 
 * @author regis rocha
 * 
 * @description Classe para realizar acesso aos dados do usuario.
 * 
 */
public class UserDao extends GenericDaoImpl {

	/**
	 * serial version
	 */
	private static final long serialVersionUID = 1061527784256192173L;

	/**
	 * Attribute for entity manager
	 */
	private EntityManager entityManager;

	/**
	 * Construtor para inicializar o entityManager.
	 * 
	 * @param EntityManager
	 */
	public UserDao(EntityManager em) {
		super(em);
		this.entityManager = em;
	}

	public void updatePasswordUser(User user) {
		super.merge(user);
	}

	public void dropUser(User user) {
		// TODO Auto-generated method stub

	}

	public void addRolesToUser(User user) {
		// TODO Auto-generated method stub

	}

	public void createRoles(User user) {
		// TODO Auto-generated method stub

	}

	/**
	 * @since 25/12/2012
	 * 
	 * @author regis rocha
	 * 
	 * @description Realiza consulta em credencial.users
	 */
	public boolean emailExist(final String email) {
		try {
			final Query query = entityManager.createQuery("SELECT u FROM users u WHERE email = :email");
			query.setParameter("email", email);
			query.getSingleResult();
		} catch (NoResultException nre) {
			return false;
		}

		return true;
	}

	/**
	 * @since 24/12/2013
	 * 
	 * @author regisrocha
	 * 
	 * @description Obtem a Role Master.
	 * 
	 * @return UserRole
	 */
	public UserRole getRoleMaster() {
		final Query query = entityManager.createQuery("SELECT ur FROM user_roles ur WHERE id_user_role = :idUserRole");
		query.setParameter("idUserRole", 1L);

		return (UserRole) query.getSingleResult();
	}
}
